namespace Billing2.Controls.CR
{
    using Billing2;
    using System;
    using System.Data;
    using System.IO;
    using System.Web.UI;
    using System.Web.UI.WebControls;
    using AjaxControlToolkit;

    public class ucCRAttachment : UserControl
    {
        protected Panel AttachmentPart;
        protected Panel AttachmentPart1;
        protected Button BtnUpload;
        private DataTable dt;
        //protected FileUpload FileUpload1;
        protected AsyncFileUpload FileUpload1;
        protected GridView gvAttachments;
        protected Panel ucAttachPart1;
        protected ucHighlight ucHighlight1;
        protected UpdatePanel UpdatePanel3;
        protected UpdatePanel updatePanel5;
        protected HiddenField xRoleID;
        protected HiddenField xTotalFileSize;

        private void BindAttachment()
        {
            this.dt = (DataTable) this.ViewState["Attachments"];
            this.gvAttachments.DataSource = this.dt;
            this.gvAttachments.DataBind();
        }

        protected void BtnUpload_Click(object sender, EventArgs e)
        {
            this.ucHighlight1.CloseAll();

            if (this.FileUpload1.HasFile)
            {
                string filename = this.FileUpload1.PostedFile.FileName.ToLower();
                if (CheckFileFormat(Path.GetExtension(filename).ToLower(), this.FileUpload1.FileBytes))
                {
                    if (this.FileUpload1.PostedFile.ContentLength < 1024 * 1024)
                    {
                        if (this.TotalFileSize < 10 * 1024 * 1024)
                        {
                            this.dt = (DataTable) this.ViewState["Attachments"];
                            this.TotalFileSize += this.FileUpload1.PostedFile.ContentLength;
                            DataRow dr = this.DT.NewRow();
                            dr["AttachmentName"] = Path.GetFileName(this.FileUpload1.FileName);
                            dr["AttachmentDetails"] = this.FileUpload1.FileBytes;
                            dr["AttachmentContentType"] = this.FileUpload1.PostedFile.ContentType;
                            this.dt.Rows.Add(dr);
                            this.dt.AcceptChanges();
                            this.ViewState["Attachments"] = this.DT;
                            this.gvAttachments.DataSource = this.DT;
                            this.gvAttachments.DataBind();
                        }
                        else
                        {
                            this.ucHighlight1.ErrorMessage = "The total attachments size have exceeded 10MB limit";
                        }
                    }
                    else
                    {
                        this.ucHighlight1.ErrorMessage = "The attached file size has to be less than 1MB";
                    }
                }
                else
                {
                    this.ucHighlight1.ErrorMessage = "The uploaded file type is not allowed";
                }
            }
        }

        bool CheckFileFormat(string extension, byte[] bytes)
        {
            switch(extension) 
            {
                    case ".jpg": return CompareFileHeader("FFD8FF", bytes);
                    case ".jpeg": return CompareFileHeader("FFD8FF", bytes);
                    case ".png": return CompareFileHeader("89504E47", bytes);
                    case ".gif": return CompareFileHeader("47494638", bytes);
                    case ".tif": return CompareFileHeader("49492A00", bytes);
                    case ".bmp": return CompareFileHeader("424D", bytes);
                    case ".pdf": return CompareFileHeader("255044462D312E", bytes);
                    case ".doc": return CompareFileHeader("D0CF11E0", bytes);
                    case ".xls": return CompareFileHeader("D0CF11E0", bytes);
                    case ".ppt": return CompareFileHeader("D0CF11E0", bytes);
                    case ".docx": return CompareFileHeader("504B0304140006000800", bytes);
                    case ".xlsx": return CompareFileHeader("504B0304140006000800", bytes);
                    case ".pptx": return CompareFileHeader("504B0304140006000800", bytes);
                    case ".rtf": return CompareFileHeader("7B5C727466", bytes);
                    case ".txt": return !CompareFileHeader("4D5A9000030000000400", bytes); //not exe
                    //case ".exe": return CompareFileHeader("4D5A9000030000000400", bytes);
                    //case ".zip": return CompareFileHeader("504B0304", bytes);
                    //case ".rar": return CompareFileHeader("52617221", bytes);
                    //case ".wav": return CompareFileHeader("57415645", bytes);
                    //case ".avi": return CompareFileHeader("41564920", bytes);
                    //case ".ram": return CompareFileHeader("2E7261FD", bytes);
                    //case ".rm": return CompareFileHeader("2E524D46", bytes);
                    //case ".rmvb": return CompareFileHeader("2E524D46", bytes);
                    //case ".mpg": return CompareFileHeader("000001BA", bytes) || CompareFileHeader("000001B3", bytes);
                    //case ".mov": return CompareFileHeader("6D6F6F76", bytes);
                    //case ".asf": return CompareFileHeader("3026B2758E66CF11", bytes);
                    //case ".mid": return CompareFileHeader("4D546864", bytes);
                default:
                    return false;
            }
        }

        bool CompareFileHeader(string magic, byte[] bytes)
        {
            int n = (int)(magic.Length / 2);
            if (bytes.Length < n)
                return false;
            string s = MyLib.HexUtility.BytesToHex(bytes, 0, n).Replace(" ", "");
            return s == magic;
        }


        protected void grwAttachments_RowDeleting(object sender, GridViewDeleteEventArgs e)
        {
            int i = e.RowIndex;
        }

        protected void gvAttachments_RowCommand(object sender, GridViewCommandEventArgs e)
        {
            if (e.CommandName.ToString().ToLower() == "removeattach")
            {
                this.DT.Rows[Convert.ToInt32(e.CommandArgument)].Delete();
                this.BindAttachment();
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.Page.IsPostBack)
            {
                this.TotalFileSize = 0;
                this.dt = new DataTable();
            }
            this.ucHighlight1.CloseAll();
        }

        public bool AttachmentPanel
        {
            set
            {
                this.AttachmentPart.Visible = value;
                this.gvAttachments.Columns[2].Visible = value;
                this.gvAttachments.Columns[0].Visible = !value;
                this.gvAttachments.Columns[1].Visible = value;
            }
        }

        public DataTable DT
        {
            get
            {
                return (DataTable) this.ViewState["Attachments"];
            }
            set
            {
                this.ViewState["Attachments"] = value;
                this.dt = value;
                this.BindAttachment();
            }
        }

        public int RoleID
        {
            get
            {
                return Convert.ToInt32(this.xRoleID.Value);
            }
            set
            {
                this.xRoleID.Value = Microsoft.Security.Application.Encoder.HtmlEncode(value.ToString());
            }
        }

        public long TotalFileSize
        {
            get
            {
                if (base.Session["TotalFileSize"] == null)
                {
                    base.Session["TotalFileSize"] = "0";
                }
                return Convert.ToInt64(base.Session["TotalFileSize"].ToString());
            }
            set
            {
                base.Session["TotalFileSize"] = value.ToString();
            }
        }
    }
}
